package com.example.uploadattachment.controller;

import com.example.uploadattachment.model.ReceiveFileEntity;
import com.example.uploadattachment.model.ResultResponse;
import com.example.uploadattachment.service.FileService;
import com.jcraft.jsch.SftpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author 何逸诚
 * @date 2023/12/6 15:37
 */
@RestController
@RequestMapping("/file")
public class UploadController {
    @Autowired
    private FileService fileService;

    @PostMapping("/uploadFileToLocal")
    public ResultResponse<ReceiveFileEntity> uploadFileToLocal(@RequestBody ReceiveFileEntity receiveFileEntity) throws SftpException, IOException {
        ReceiveFileEntity fileEntity = fileService.uploadFile(receiveFileEntity, false);
        if (fileEntity != null) {
            return ResultResponse.ok("上传文件到本地成功", fileEntity);
        } else {
            return ResultResponse.ok("上传文件失败，请联系管理员");
        }
    }

    @PostMapping("/uploadFileToSftp")
    public ResultResponse<ReceiveFileEntity> uploadFileToSftp(@RequestBody ReceiveFileEntity receiveFileEntity) throws SftpException, IOException {
        ReceiveFileEntity fileEntity = fileService.uploadFile(receiveFileEntity, true);
        if (fileEntity != null) {
            return ResultResponse.ok("上传文件到服务器成功", fileEntity);
        } else {
            return ResultResponse.ok("上传文件失败，请联系管理员");
        }
    }
}
